<template>
  <div class="smart-search-page">
    <!-- 搜索输入框 -->
    <div class="search-section">
      <van-search
        v-model="searchKeyword"
        shape="round"
        placeholder="请输入关键词"
        @search="handleSearch"
      />
    </div>

    <!-- 热门标签区域 -->
    <div class="tags-section">
      <div class="tags-header">
        <span class="section-title">热门标签</span>
        <van-button 
          size="mini" 
          type="primary" 
          plain
          @click="openTagPopup"
        >
          更多
        </van-button>
      </div>
      <div class="hot-tags">
        <div
          v-for="tag in hotTags"
          :key="tag"
          :class="['tag-item', { 'tag-item-selected': selectedTags.includes(tag) }]"
          @click="toggleTag(tag)"
        >
          {{ tag }}
        </div>
      </div>
    </div>

    <!-- 已选标签展示区域 -->
    <div v-if="selectedTags.length > 0" class="selected-tags-section">
      <div class="tags-header">
        <span class="section-title">已选标签</span>
      </div>
      <div class="selected-tags-container">
        <div class="selected-tags-grid">
          <div
            v-for="tag in selectedTags"
            :key="tag"
            class="selected-tag"
          >
            <span>{{ tag }}</span>
            <van-icon name="cross" @click="removeTag(tag)" class="tag-close-icon" />
          </div>
        </div>
      </div>
    </div>

    <!-- 用户推荐列表 -->
    <div class="users-section">
      <div class="section-title">推荐用户</div>
      <div v-if="loading" class="loading-container">
        <van-loading type="spinner" size="24px">加载中...</van-loading>
      </div>
      <div v-else-if="recommendUsers.length > 0" class="users-list">
        <div
          v-for="user in recommendUsers"
          :key="user.id"
          class="user-card"
        >
          <div class="user-header">
            <van-image
              round
              width="50"
              height="50"
              fit="cover"
              :src="user.avatarUrl"
              class="user-avatar"
            />
            <div class="user-info">
              <div class="user-name">{{ user.username }}</div>
              <div class="user-profile">{{ user.personalProfile || '暂无简介' }}</div>
            </div>
            <van-button
              size="mini"
              :type="user.isFollowed ? 'default' : 'primary'"
              @click="handleFollowClick(user)"
              class="follow-btn"
            >
              {{ user.isFollowed ? '已关注' : '关注' }}
            </van-button>
          </div>
          <div class="user-tags">
            <van-tag
              v-for="tag in user.tags"
              :key="tag"
              type="success"
              plain
              class="user-tag-item"
            >
              {{ tag }}
            </van-tag>
          </div>
        </div>
      </div>
      <div v-else class="empty-container">
        <van-empty description="暂无推荐用户" />
      </div>
    </div>

    <!-- 标签选择浮窗 -->
    <van-popup
      v-model:show="showTagPopup"
      position="bottom"
      :style="{ height: '70%' }"
      round
    >
      <div class="tag-popup">
        <div class="popup-header">
          <span class="popup-title">选择标签</span>
          <van-button size="mini" type="primary" @click="confirmTags">完成</van-button>
        </div>
        <div class="popup-content">
          <!-- 系统标签 -->
          <div class="tag-category">
            <div class="category-title">系统标签</div>
            <div class="tag-list">
              <div
                v-for="tag in systemTags"
                :key="tag"
                :class="['tag-item', { 'tag-item-selected': tempSelectedTags.includes(tag) }]"
                @click="toggleTempTag(tag)"
              >
                {{ tag }}
              </div>
            </div>
          </div>
          <!-- 自定义标签 -->
          <div class="tag-category">
            <div class="category-title">自定义标签</div>
            <div class="custom-tag-input">
              <van-field
                v-model="customTagInput"
                placeholder="输入自定义标签"
                @keyup.enter="addCustomTag"
                class="custom-input-field"
              />
              <button
                @click="addCustomTag"
                class="add-tag-btn"
                :disabled="!customTagInput.trim()"
              >
                <van-icon name="plus" size="18" />
              </button>
            </div>
            <div class="tag-list">
              <div
                v-for="tag in customTags"
                :key="tag"
                :class="['tag-item', { 'tag-item-selected': tempSelectedTags.includes(tag) }]"
                @click="toggleTempTag(tag)"
              >
                {{ tag }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </van-popup>

    <!-- 用户详情浮窗（关注时显示） -->
    <van-popup
      v-model:show="showUserDetailPopup"
      position="bottom"
      :style="{ height: '60%' }"
      round
    >
      <div class="user-detail-popup">
        <div class="popup-header">
          <span class="popup-title">用户详情</span>
          <van-icon name="cross" @click="showUserDetailPopup = false" />
        </div>
        <div class="popup-content" v-if="selectedUser">
          <div class="detail-user-header">
            <van-image
              round
              width="80"
              height="80"
              fit="cover"
              :src="selectedUser.avatarUrl"
            />
            <div class="detail-user-name">{{ selectedUser.username }}</div>
            <div class="detail-user-profile">{{ selectedUser.personalProfile || '暂无简介' }}</div>
          </div>
          <div class="detail-user-tags">
            <van-tag
              v-for="tag in selectedUser.tags"
              :key="tag"
              type="success"
              plain
              class="detail-tag-item"
            >
              {{ tag }}
            </van-tag>
          </div>
          <div class="add-friend-section">
            <van-field
              v-model="addFriendReason"
              type="textarea"
              rows="3"
              placeholder="填写添加好友的理由"
              maxlength="100"
            />
            <van-button
              type="primary"
              block
              @click="handleAddFriend"
              class="add-friend-btn"
            >
              发送好友申请
            </van-button>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { showToast } from 'vant';
import { getAllTagAndCategoryToSearch } from '../api/tagApi';
import { getRecommend, getUsersByTags } from '../api/userApi';

// 搜索关键词
const searchKeyword = ref('');

// 热门标签
const hotTags = ref<string[]>([]);

// 系统标签（从API获取）
const systemTags = ref<string[]>([]);

// 自定义标签
const customTags = ref<string[]>([]);

// 已选标签
const selectedTags = ref<string[]>([]);

// 临时选中的标签（浮窗中选择）
const tempSelectedTags = ref<string[]>([]);

// 自定义标签输入
const customTagInput = ref('');

// 浮窗显示状态
const showTagPopup = ref(false);
const showUserDetailPopup = ref(false);

// 推荐用户列表
const recommendUsers = ref<any[]>([]);
const loading = ref(false);

// 当前选中的用户（用于详情浮窗）
const selectedUser = ref<any>(null);
const addFriendReason = ref('');

// 切换标签选中状态
const toggleTag = (tag: string) => {
  const index = selectedTags.value.indexOf(tag);
  if (index > -1) {
    selectedTags.value.splice(index, 1);
  } else {
    selectedTags.value.push(tag);
  }
  // 触发搜索
  searchUsers();
};

// 移除标签
const removeTag = (tag: string) => {
  const index = selectedTags.value.indexOf(tag);
  if (index > -1) {
    selectedTags.value.splice(index, 1);
    // 触发搜索
    searchUsers();
  }
};

// 切换临时标签（浮窗中）
const toggleTempTag = (tag: string) => {
  const index = tempSelectedTags.value.indexOf(tag);
  if (index > -1) {
    tempSelectedTags.value.splice(index, 1);
  } else {
    tempSelectedTags.value.push(tag);
  }
};

// 添加自定义标签
const addCustomTag = () => {
  const tag = customTagInput.value.trim();
  if (tag && !customTags.value.includes(tag) && !systemTags.value.includes(tag)) {
    customTags.value.push(tag);
    customTagInput.value = '';
  } else if (tag) {
    showToast('标签已存在');
  }
};

// 确认标签选择
const confirmTags = () => {
  selectedTags.value = [...tempSelectedTags.value];
  showTagPopup.value = false;
  // 触发搜索
  searchUsers();
};

// 打开标签浮窗时，初始化临时选中标签
const openTagPopup = () => {
  tempSelectedTags.value = [...selectedTags.value];
  showTagPopup.value = true;
};

// 搜索用户
const handleSearch = () => {
  searchUsers();
};

// 搜索用户（根据关键词和标签）
const searchUsers = async () => {
  loading.value = true;
  try {
    // 如果有选中的标签，使用标签搜索
    if (selectedTags.value.length > 0) {
      const res: any = await getUsersByTags(selectedTags.value);
      if (res.code === 200 && res.data && res.data.length > 0) {
        recommendUsers.value = processUserData(res.data);
      } else {
        // 如果API返回空数据，使用假数据过滤
        const mockUsers = generateMockUsers();
        recommendUsers.value = mockUsers.filter(user => 
          user.tags.some(tag => selectedTags.value.includes(tag))
        );
      }
    } else {
      // 否则获取推荐用户
      const res: any = await getRecommend('1', '10');
      if (res.code === 200 && res.data && res.data.length > 0) {
        recommendUsers.value = processUserData(res.data);
      } else {
        // 如果API返回空数据，使用假数据
        recommendUsers.value = generateMockUsers();
      }
    }
  } catch (error) {
    console.error('搜索用户失败:', error);
    // API失败时使用假数据
    if (selectedTags.value.length > 0) {
      const mockUsers = generateMockUsers();
      recommendUsers.value = mockUsers.filter(user => 
        user.tags.some(tag => selectedTags.value.includes(tag))
      );
    } else {
      recommendUsers.value = generateMockUsers();
    }
  } finally {
    loading.value = false;
  }
};

// 处理用户数据（解析标签等）
const processUserData = (users: any[]) => {
  return users.map((user: any) => {
    // 解析标签
    if (user.tags && typeof user.tags === 'string') {
      try {
        user.tags = JSON.parse(user.tags);
      } catch (e) {
        user.tags = [];
      }
    } else if (!user.tags) {
      user.tags = [];
    }
    // 初始化关注状态
    if (user.isFollowed === undefined) {
      user.isFollowed = false;
    }
    return user;
  });
};

// 处理关注按钮点击
const handleFollowClick = (user: any) => {
  selectedUser.value = user;
  addFriendReason.value = '';
  showUserDetailPopup.value = true;
};

// 处理添加好友
const handleAddFriend = () => {
  if (!addFriendReason.value.trim()) {
    showToast('请填写添加好友的理由');
    return;
  }
  // TODO: 调用添加好友API
  console.log('添加好友:', selectedUser.value?.id, addFriendReason.value);
  showToast('好友申请已发送');
  if (selectedUser.value) {
    selectedUser.value.isFollowed = true;
  }
  showUserDetailPopup.value = false;
  addFriendReason.value = '';
};

// 加载标签数据
const loadTags = async () => {
  try {
    const res: any = await getAllTagAndCategoryToSearch();
    if (res.code === 200) {
      // 处理标签数据，提取所有标签
      const allTags: string[] = [];
      if (Array.isArray(res.data)) {
        res.data.forEach((category: any) => {
          if (category.children && Array.isArray(category.children)) {
            category.children.forEach((child: any) => {
              if (child.text && !allTags.includes(child.text)) {
                allTags.push(child.text);
              }
            });
          }
        });
      }
      systemTags.value = allTags;
      // 热门标签取前10个
      hotTags.value = allTags.slice(0, 10);
    }
  } catch (error) {
    console.error('加载标签失败:', error);
  }
};

// 生成假数据
const generateMockUsers = () => {
  const mockUsers = [
    {
      id: 1,
      username: '张小明',
      avatarUrl: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg',
      personalProfile: '热爱编程，专注于前端开发，喜欢探索新技术。希望找到志同道合的伙伴一起学习进步！',
      tags: ['前端', 'Vue', 'JavaScript', 'React'],
      isFollowed: false,
      planetCode: '10001'
    },
    {
      id: 2,
      username: '李小红',
      avatarUrl: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg',
      personalProfile: 'Java后端开发工程师，有3年工作经验。喜欢研究分布式系统和微服务架构。',
      tags: ['Java', 'Spring', '后端', '微服务'],
      isFollowed: false,
      planetCode: '10002'
    },
    {
      id: 3,
      username: '王小强',
      avatarUrl: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg',
      personalProfile: 'Python全栈开发，对数据分析和机器学习感兴趣。希望找到一起做项目的伙伴。',
      tags: ['Python', 'Django', '数据分析', '机器学习'],
      isFollowed: false,
      planetCode: '10003'
    },
    {
      id: 4,
      username: '刘小美',
      avatarUrl: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg',
      personalProfile: 'UI/UX设计师，擅长移动端设计。喜欢简洁优雅的设计风格，追求用户体验的极致。',
      tags: ['UI设计', 'UX设计', '移动端', 'Figma'],
      isFollowed: false,
      planetCode: '10004'
    },
    {
      id: 5,
      username: '陈小刚',
      avatarUrl: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg',
      personalProfile: 'Go语言开发工程师，专注于云原生和容器化技术。有丰富的Kubernetes实战经验。',
      tags: ['Go', 'Kubernetes', '云原生', 'Docker'],
      isFollowed: false,
      planetCode: '10005'
    },
    {
      id: 6,
      username: '赵小芳',
      avatarUrl: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg',
      personalProfile: '产品经理，有5年互联网产品经验。擅长用户研究和产品设计，希望找到技术伙伴一起创业。',
      tags: ['产品经理', '用户研究', '产品设计', '创业'],
      isFollowed: false,
      planetCode: '10006'
    }
  ];
  return mockUsers;
};

// 页面加载时初始化
onMounted(() => {
  loadTags();
  // 先加载假数据
  recommendUsers.value = generateMockUsers();
  // 然后尝试加载真实数据，如果失败则使用假数据
  searchUsers().catch(() => {
    // 如果API调用失败，保持假数据
  });
});
</script>

<style scoped>
.smart-search-page {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 20px;
}

/* 搜索区域 */
.search-section {
  background-color: #fff;
  padding: 8px 0;
}

/* 标签区域 */
.tags-section {
  background-color: #fff;
  padding: 16px;
  margin-top: 8px;
}

.tags-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #323233;
}

.hot-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tag-item {
  cursor: pointer;
  padding: 6px 16px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, #f5f7fa 0%, #e8ecf0 100%);
  color: #606266;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  user-select: none;
}

.tag-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  background: linear-gradient(135deg, #e8ecf0 0%, #dde1e6 100%);
}

.tag-item-selected {
  background: linear-gradient(135deg, #64b5f6 0%, #42a5f5 100%);
  color: #fff;
  border-color: #42a5f5;
  box-shadow: 0 4px 12px rgba(66, 165, 245, 0.3);
}

.tag-item-selected:hover {
  background: linear-gradient(135deg, #42a5f5 0%, #2196f3 100%);
  box-shadow: 0 6px 16px rgba(66, 165, 245, 0.4);
}

/* 已选标签区域 */
.selected-tags-section {
  background-color: #fff;
  padding: 16px;
  margin-top: 8px;
}

.selected-tags-container {
  max-height: 120px;
  overflow-y: auto;
}

.selected-tags-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.selected-tag {
  margin: 0;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px 6px 16px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  background: linear-gradient(135deg, #64b5f6 0%, #42a5f5 100%);
  color: #fff;
  box-shadow: 0 2px 8px rgba(66, 165, 245, 0.3);
  transition: all 0.3s ease;
}

.selected-tag:hover {
  box-shadow: 0 4px 12px rgba(66, 165, 245, 0.4);
  transform: translateY(-1px);
}

.tag-close-icon {
  cursor: pointer;
  padding: 2px;
  border-radius: 50%;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.tag-close-icon:hover {
  background-color: rgba(255, 255, 255, 0.3);
  transform: scale(1.1);
}

/* 用户推荐区域 */
.users-section {
  margin-top: 8px;
  padding: 16px;
}

.users-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.user-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.user-header {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 12px;
}

.user-avatar {
  flex-shrink: 0;
}

.user-info {
  flex: 1;
  min-width: 0;
}

.user-name {
  font-size: 16px;
  font-weight: 500;
  color: #323233;
  margin-bottom: 4px;
}

.user-profile {
  font-size: 14px;
  color: #969799;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

.follow-btn {
  flex-shrink: 0;
}

.user-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.user-tag-item {
  margin: 0;
}

.loading-container,
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
  background-color: #fff;
  border-radius: 8px;
}

/* 标签选择浮窗 */
.tag-popup {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ebedf0;
}

.popup-title {
  font-size: 18px;
  font-weight: 500;
}

.popup-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.tag-category {
  margin-bottom: 24px;
}

.category-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 12px;
  color: #323233;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.custom-tag-input {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  align-items: center;
}

.custom-input-field {
  flex: 1;
}

.add-tag-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: none;
  background: linear-gradient(135deg, #64b5f6 0%, #42a5f5 100%);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(66, 165, 245, 0.3);
  flex-shrink: 0;
}

.add-tag-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #42a5f5 0%, #2196f3 100%);
  box-shadow: 0 6px 16px rgba(66, 165, 245, 0.4);
  transform: translateY(-2px) scale(1.05);
}

.add-tag-btn:active:not(:disabled) {
  transform: translateY(0) scale(0.98);
}

.add-tag-btn:disabled {
  background: #e0e0e0;
  color: #bdbdbd;
  cursor: not-allowed;
  box-shadow: none;
}

/* 用户详情浮窗 */
.user-detail-popup {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.detail-user-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24px 16px;
  border-bottom: 1px solid #ebedf0;
}

.detail-user-name {
  font-size: 18px;
  font-weight: 500;
  margin-top: 12px;
  margin-bottom: 8px;
}

.detail-user-profile {
  font-size: 14px;
  color: #969799;
  text-align: center;
}

.detail-user-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 16px;
  border-bottom: 1px solid #ebedf0;
}

.detail-tag-item {
  margin: 0;
}

.add-friend-section {
  padding: 16px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.add-friend-btn {
  margin-top: 16px;
}
</style>

